﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using CanDoo;
using CanDoo.Core;
using CanDoo.Core.Data;
using CanDoo.Data;
using CanDoo.Extensions;
using CanDoo.Oil.Core.Contracts;
using CanDoo.Oil.Core.Models;
using CanDoo.Oil.Core.DTOs;

namespace CanDoo.Oil.Core.Services
{
    /// <summary>
    /// 业务实现——金额变动日志
    /// </summary>
    public class MoneyChangeService : CanDoo.Data.Entity.Services.ServiceBase<MoneyChange>, IMoneyChangeContract
    {
        public ICustomerContract CustomerContract { get; set; }
        public IMoneyChangeContract MoneyChangeContract { get; set; }
        public MoneyChangeService()
        {
        
        }

        public OperationResult RechargeReq(RechargeReqInfo rechargeReqInfo)
        {
            var result = OperationResult.Success;
            using (DbScopeFactory.CreateReadOnly())
            {
                var customer = CustomerContract.FirstOrDefault(p => p.CardNo == rechargeReqInfo.cardNo);
                if (customer == null)
                {
                    result.ResultType = OperationResultType.Error;
                    result.Message = "卡号["+ rechargeReqInfo.cardNo + "]不存在";
                    return result;
                }
            }
            return result;
        }

        public OperationResult Recharge(RechargeRspInfo rechargeRspInfo)
        {
            var result = OperationResult.Success;
            using (var scope = DbScopeFactory.Create())
            {
                var customer = CustomerContract.FirstOrDefault(p => p.CardNo == rechargeRspInfo.cardNo);
                if (customer == null)
                {
                    result.ResultType = OperationResultType.Error;
                    result.Message = "卡号[" + rechargeRspInfo.cardNo + "]不存在";
                    return result;
                }

                var nEntity = new MoneyChange();
                nEntity.Id = IdMaker.NewId();
                nEntity.GroupId = nEntity.Id;
                nEntity.MoneyType = 101;
                nEntity.Code = rechargeRspInfo.voucherNo;
                nEntity.UserId = customer.Id;
                nEntity.Name = "客户[" + customer.CardNo + "]通过POS机充值[" + rechargeRspInfo.account * 0.01 + "]元";
                nEntity.MoneyBefore = customer.Balance;
                nEntity.Money = rechargeRspInfo.account * 0.01;
                nEntity.MoneyAfter = customer.Balance + nEntity.Money;
                MoneyChangeContract.AddEntity(nEntity);

                customer.Balance = customer.Balance + nEntity.Money;
                CustomerContract.Update(customer);

                return  scope.SaveChanges()>0? new OperationResult(OperationResultType.Success,"充值成功"):new OperationResult(OperationResultType.Error,"数据保存失败");
            }
        }
    }
}
